// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/user/api/SysRoleApi'

import ComClass from '@api/ComQuery'
import ListClass from '@api/user/model/SysRoleDto'
import DelClass from '@api/user/model/SysRoleDeleteReq'

const AddClass = ListClass
const EditClass = ListClass

const CLIENT = CORE.grpcCLIENT(Client)
const COM = [ComClass, 'comQuery']

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 列表 —————————————————————————————— //

  async getList(param, TIP = '查询列表') {
    const DTO = CORE.grpcDTO(ListClass, param, COM)
    const resp = await CORE.grpc(TIP, CLIENT, 'sysRoleQuery', DTO)
    return [resp.comQuery.totalCount, resp.content || []]
  },
  transList(arr, { state: { DICT: { ROLE_BTN } } }) {
    arr.forEach((item) => {
      item.menuIdStr = item.menuId.join()
      item.regionIdStr = item.regionId.join()
      item.logisticsAppMenuIdsStr = item.logisticsAppMenuIds.join()
      item.staffAppMenuIdsStr = item.staffAppMenuIds.join()

      if (item.roleType === 1 && item.rolePlatform !== 2) {
        item.roleBtn = ROLE_BTN.map(([, , key], i) => item[key] === 1 ? i + 1 : 0).filter((id) => id)
      }
    })
    return arr
  },

  // —————————————————————————————— 增 —————————————————————————————— //

  transAdd(obj, { state: { DICT: { ROLE_BTN } } }) {
    const one = { ...obj }
    ROLE_BTN.forEach(([, , key], i) => (one[key] = obj.roleBtn.includes(i + 1) ? 1 : 2))
    return one
  },
  async add(one, TIP = '新增') {
    const DTO = CORE.grpcDTO(AddClass, one)
    await CORE.grpc(TIP, CLIENT, 'sysRoleSave', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 改 —————————————————————————————— //

  transEditToAdd: true,
  async edit(one, TIP = '修改') {
    const DTO = CORE.grpcDTO(EditClass, one)
    await CORE.grpc(TIP, CLIENT, 'sysRoleUpdate', DTO)
    return CORE.grpcOK(TIP)
  },

  // —————————————————————————————— 删 —————————————————————————————— //

  async del({ id }, TIP = '删除') {
    const DTO = CORE.grpcDTO(DelClass, { ids: id })
    await CORE.grpc(TIP, CLIENT, 'sysRoleDelete', DTO)
    return CORE.grpcOK(TIP)
  },
}
